<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <div style="width: 100%; display: flex; flex-direction: column; height: 100vh;">
      <div style="display: flex; align-items: center; padding: 1px 15px; position: relative;">
        <!-- 左侧新建按钮 -->
        <el-button class="idoo-details-add">新建</el-button>
        <!-- 右侧信息区域：垂直展示 -->
        <div style="display: flex; flex-direction: column; margin-left: 10px;">
          <span style="font-size: 15px;"> <el-button type="primary" link @click="handleBack">客户</el-button></span>
          <div style="display: flex; align-items: center; font-size: 14px; margin-top: 4px;">
            <span class="sub-title">{{ detailsTitle }}</span>
            <el-tooltip content="保存" placement="top" v-if="isFormChanged">
              <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleSave">
                <UploadFilled />
              </el-icon>
            </el-tooltip>
            <el-tooltip content="撤销修改" placement="top" v-if="isFormChanged">
              <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleRevert">
                <RefreshLeft />
              </el-icon>
            </el-tooltip>
          </div>
        </div>
      </div>
      <!-- 带阴影的分割线 -->
      <div class="divider"></div>
      <!-- 后续内容区域：背景色为淡灰色，填满剩余区域 -->
      <div class="content-section">
        <div style="display: flex; width: 100%;">
  
          <!-- 左侧：无阴影的Card，占整体宽度的65%，用于表单的详情数据 -->
          <div style="height: auto; width: 65%; margin-right: 10px;">
            <el-card style="box-shadow: none;">
              <el-form :model="cusForm" style="width: 100%;">
                <el-form-item label="" prop="cusName">
                  <el-input v-model="cusForm.cusName"
                    style="font-size: 30px; height: 60px; line-height: 60px; width: 70%; padding: 10px;"
                    class="idoo-details-input" placeholder="编码客户名称：例如：阿里巴巴集团控股有限公司"></el-input>
                </el-form-item>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="客户类型">
                      <el-select v-model="cusForm.cusType" placeholder="请选择客户类型" style="width: 70%;"
                        class="idoo-details-select">
                        <el-option v-for="item in codeStore().getSystemCode('CRM_CUS_TYPE') as CodeValueType[]"
                          :key="item.bizValue" :label="item.bizName" :value="item.bizValue" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="客户行业">
                      <el-input v-model="cusForm.cusIndustry" style="width: 100%;" class="idoo-details-input"
                        placeholder="例如：消费、金融、制造业、食品加工..."></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="客户职位">
                      <el-input v-model="cusForm.cusPosition" style="width: 100%;" class="idoo-details-input"
                        placeholder="例如：销售经理、总经理、董事长、文员..."></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="客户等级">
                      <el-rate v-model="cusForm.cusLevel" size="large" style="width: 100%;" clearable />
                      <!-- <el-input v-model="cusForm.cusLevel" style="width: 100%;" class="idoo-details-input"
                        placeholder="例如：0、1"></el-input> -->
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="客户规模">
                      <el-select v-model="cusForm.cusScale" placeholder="请选择客户规模" style="width: 70%;"
                        class="idoo-details-select">
                        <el-option v-for="item in codeStore().getSystemCode('CRM_CUS_SCALE') as CodeValueType[]"
                          :key="item.bizValue" :label="item.bizName" :value="item.bizValue" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="电话">
                      <el-input v-model="cusForm.cusPhone" style="width: 100%;" class="idoo-details-input"
                        placeholder="例如：18742536182 、 0432-2762558"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="邮箱">
                      <el-input v-model="cusForm.cusEmail" style="width: 100%;" class="idoo-details-input"
                        placeholder="例如：1750276460@qq.com"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="地址">
                      <el-input v-model="cusForm.cusAddress" style="width: 100%;" class="idoo-details-input"
                        placeholder="例如：浙江省杭州市滨江区网商路699号1号楼5楼"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="客户官网">
                      <el-input v-model="cusForm.cusWeburl" style="width: 100%;" class="idoo-details-input"
                        placeholder="例如：https://www.alibaba.com/"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="客户来源">
                      <el-input v-model="cusForm.cusSource" style="width: 100%;" class="idoo-details-input"
                        placeholder="例如：销售、个人、中介"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                  </el-col>
                </el-row>
              </el-form>
            </el-card>
          </div>
  
          <!-- 右侧：修改记录区域，保持背景色 -->
          <div style="width: 35%; padding: 10px; height: calc(100vh - 180px); overflow-y: auto;">
            <!-- 修改记录内容 -->
            <div v-if="recordInfos">
              <div v-for="(item) in recordInfos" :key="item.dateGroup">
                <!-- 标题 -->
                <div style="display: flex; align-items: center; margin-bottom: 15px;">
                  <div class="divider" style="flex: 1;"></div>
                  <span style="color: rgba(55, 65, 81, 0.76); opacity: 0.5; margin: 0 16px; white-space: nowrap;">
                    {{ item.dateGroup }}
                  </span>
                  <div class="divider" style="flex: 1;"></div>
                </div>
                <!-- 数据 -->
                <div v-for="(child) in item.recordEntityList" :key="child.id" style="margin-top: 15px;">
                  <div>
                    <span style="font-weight: 600; font-size: medium;"> {{ child.createUser }} :</span>
                    <span style="color: rgba(55, 65, 81, 0.76) !important; font-size: 15px; margin-left: 15px;"> {{
                      child.createTime }}</span>
                  </div>
                  <div style="margin:5px 10px;" v-if="child.eventType == '修改'">
                    <span style="margin-left: 10px; color: rgba(1, 128, 165); font-weight: bold;">·</span>
                    <span style="margin-left: 10px; font-size: 15px; font-style: italic; color: rgba(1, 128, 165); "> {{
                      child.eventType }} </span>
                    <span style="margin-left: 10px;"> {{ child.oldValue }} </span>
                    <span style=" margin-left: 10px; font-style: italic; font-weight: bolder;">
                      <el-icon>
                        <Right />
                      </el-icon> </span>
                    <span style=" margin-left: 10px; color: rgba(1, 128, 165); font-weight: bold;"> {{ child.newValue }}
                    </span>
                    <span style=" margin-left: 10px; font-style: italic; color: rgba(55, 65, 81, 0.76) !important; "> ({{
                      child.filedName }}) </span>
                  </div>
                  <div style="margin:5px 10px;" v-if="child.eventType == '新建'">
                    <span style="margin-left: 10px; font-size: 15px; font-style: italic; color: rgba(1, 128, 165); ">
                      新建了数据 </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  <script setup lang="ts">
  import { onMounted, ref, watch } from 'vue';
  import { useRoute } from 'vue-router';
  import { UploadFilled, RefreshLeft } from '@element-plus/icons-vue';
  import router from '@/router';
  import { ElMessageBox } from 'element-plus';
  import { codeStore } from '@/stores/codeStore';
  import { _getCustomerInfo, _getRecordInfos, _modifyCustomerInfo, _saveCustomerInfo } from '@/api/generic/quotataion/list-api';
  import type { CustomerFrom } from '@/types/customer/types';
  import type { CodeValueType } from '@/types/piniatypes';
  import { getChangedFields, updateWrapperBuilder } from '@/utils/form/updateFormHelper';
  import type { BaseRecordVo } from '@/types/basetypes';
  import { Right } from '@element-plus/icons-vue'
  const route = useRoute();
  const detailsTitle = ref("");
  const isFormChanged = ref(false);
  const originalFormData = ref<CustomerFrom>({});
  const recordInfos = ref<BaseRecordVo[]>([]);
  const handleBack = () => {
    if (isFormChanged.value) {
      ElMessageBox.confirm('是否保存当前数据？', '确认保存', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        await handleSave();
      }).catch(() => {
        router.push({ path: route.fullPath.replace('/add', '') })
      })
    } else {
      router.push({ path: route.fullPath.replace('/add', '') })
    }
  }
  
  const routParams = route.query;
  // 初始化表单数据
  const cusForm = ref<CustomerFrom>({})
  const resetForm = () => {
    originalFormData.value = JSON.parse(JSON.stringify(cusForm.value));
    detailsTitle.value = cusForm.value.cusName || '新建';
    isFormChanged.value = false;
  }
  
  // 监听表单变化
  watch(() => cusForm.value, (newVal) => {
    isFormChanged.value = JSON.stringify(newVal) !== JSON.stringify(originalFormData.value);
  }, { deep: true });
  
  //初始化加载数据
  onMounted(async () => {
    originalFormData.value = JSON.parse(JSON.stringify(cusForm.value));
    detailsTitle.value = '新建'
    //获取用户数据
    if (routParams.id) {
      //编辑
      const res = await _getCustomerInfo({ id: routParams.id.toString() });
      if (res.code === 200 && res.data) {
        cusForm.value = res.data;
        originalFormData.value = JSON.parse(JSON.stringify(res.data));
        detailsTitle.value = cusForm.value.cusName || '';
      }
      const rres = await _getRecordInfos({ id: routParams.id.toString() });
      console.log(rres.code);
      if (rres.code === 200 && rres.data) {
        recordInfos.value = rres.data;
      }
    }
  });
  
  // 保存处理函数
  const handleSave = async () => {
    //TODO 表单校验
    const formData = cusForm.value
    try {
      const i = getChangedFields(originalFormData.value, formData)
      console.log(i);
      let res;
      if (routParams.id) {
        const upWrap = updateWrapperBuilder(formData, i); // 传递 formData 作为参数
        res = await _modifyCustomerInfo(upWrap); // 使用 upWrap 作为参数
      } else {
        res = await _saveCustomerInfo(formData);
      }
      if (res && res.code === 200) {
        resetForm();
      }
    } catch (error) {
      console.error('保存失败:', error);
    }
  };
  
  // 撤销修改，还原表单
  const handleRevert = () => {
    cusForm.value = JSON.parse(JSON.stringify(originalFormData.value));
  };
  </script>
  <style scoped>
  :deep(.el-input__inner) {
    --el-input-inner-height: none;
  }
  
  :deep(.el-card__body) {
    padding: 1% !important;
    justify-content: unset !important;
  }
  
  .hover-icon {
    cursor: pointer;
    transition: transform 0.2s ease;
  }
  
  .hover-icon:hover {
    transform: translateY(-2px);
  }
  
  .sub-title {
    font-size: 14px;
    color: #666;
  }
  
  .divider {
    width: 100%;
    height: 1px;
    background-color: #ccc;
    margin-top: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .content-section {
    flex: 1;
    width: 100%;
    padding: 15px;
    background-color: #f5f5f5;
    box-sizing: border-box;
  }
  
  .demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
  }
  
  .demo-tabs {
    position: relative;
    width: 100%;
  }
  
  :deep(.el-tabs__nav-wrap::after) {
    position: absolute;
    content: '';
    width: 100%;
    height: 2px;
    background-color: var(--el-border-color-light);
    bottom: 0;
    left: 0;
    z-index: 1;
  }
  
  :deep(.el-tabs__nav.is-top) {
    margin-left: 10px
  }
  
  :deep(.el-tabs__header) {
    width: 100%;
    margin-bottom: 0;
  }
  
  :deep(.el-tabs__nav-wrap) {
    width: 100%;
  }
  </style>
  